import axios from './api/axios';

// 模拟数据 - 只在开发环境使用
const mockData = {
  users: [
    {
      id: 1,
      name: '张三',
      email: 'zhangsan@example.com',
      avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    },
    {
      id: 2,
      name: '李四',
      email: 'lisi@example.com',
      avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
    },
  ],
  
  trades: [
    { id: 1, symbol: 'BTC/USDT', price: 45000.50, quantity: 0.5, side: 'buy', status: 'filled', created_at: '2024-01-01 10:00:00' },
    { id: 2, symbol: 'ETH/USDT', price: 3000.75, quantity: 2.0, side: 'sell', status: 'filled', created_at: '2024-01-01 11:30:00' },
    { id: 3, symbol: 'SOL/USDT', price: 100.25, quantity: 10.0, side: 'buy', status: 'partial', created_at: '2024-01-01 12:15:00' },
    { id: 4, symbol: 'BNB/USDT', price: 350.80, quantity: 1.5, side: 'buy', status: 'pending', created_at: '2024-01-01 13:45:00' },
    { id: 5, symbol: 'BTC/USDT', price: 45500.25, quantity: 0.3, side: 'sell', status: 'filled', created_at: '2024-01-01 14:20:00' },
  ],
  
  markets: [
    { symbol: 'BTC/USDT', price: 45200.30, change_24h: 2.5, volume_24h: 12345678.90 },
    { symbol: 'ETH/USDT', price: 3050.45, change_24h: -1.2, volume_24h: 9876543.21 },
    { symbol: 'SOL/USDT', price: 102.75, change_24h: 5.8, volume_24h: 5678901.23 },
    { symbol: 'BNB/USDT', price: 352.10, change_24h: 0.8, volume_24h: 3456789.45 },
  ],
};

// 模拟延迟函数
const mockDelay = (ms: number = Math.random() * 400 + 200) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

// 用户相关API
export const userApi = {
  // 获取用户列表
  getUsers: async () => {
    // 在开发环境中使用模拟数据
    if (process.env.NODE_ENV === 'development') {
      await mockDelay();
      console.log('使用模拟数据: /api/users');
      return { code: 200, data: mockData.users, message: 'success' };
    }
    return axios.get('/users');
  },
  
  // 获取当前用户信息
  getCurrentUser: async () => {
    if (process.env.NODE_ENV === 'development') {
      await mockDelay();
      // 返回第一个用户作为当前用户
      const currentUser = mockData.users[0];
      console.log('使用模拟数据: /api/users/me');
      return { code: 200, data: currentUser, message: 'success' };
    }
    return axios.get('/users/me');
  },
  
  // 更新用户信息
  updateUser: (data: any) => axios.put('/users/me', data),
};

// 交易相关API
export const tradeApi = {
  // 获取交易列表
  getTrades: async (params?: {
    page?: number;
    limit?: number;
    symbol?: string;
    side?: string;
    status?: string;
  }) => {
    if (process.env.NODE_ENV === 'development') {
      await mockDelay();
      let filteredTrades = [...mockData.trades];
      
      // 应用筛选条件
      if (params?.symbol) {
        filteredTrades = filteredTrades.filter(t => t.symbol === params.symbol);
      }
      if (params?.side) {
        filteredTrades = filteredTrades.filter(t => t.side === params.side);
      }
      if (params?.status) {
        filteredTrades = filteredTrades.filter(t => t.status === params.status);
      }
      
      // 应用分页
      const page = params?.page || 1;
      const limit = params?.limit || 10;
      const start = (page - 1) * limit;
      const end = start + limit;
      const paginatedTrades = filteredTrades.slice(start, end);
      
      console.log(`使用模拟数据: /api/trades`);
      return {
        code: 200,
        data: {
          list: paginatedTrades,
          total: filteredTrades.length,
          page,
          limit
        },
        message: 'success'
      };
    }
    return axios.get('/trades', { params });
  },
  
  // 创建交易
  createTrade: async (data: {
    symbol: string;
    price: number;
    quantity: number;
    side: 'buy' | 'sell';
  }) => {
    if (process.env.NODE_ENV === 'development') {
      await mockDelay();
      const newTrade = {
        id: Date.now(),
        ...data,
        status: 'pending',
        created_at: new Date().toLocaleString()
      };
      mockData.trades.unshift(newTrade);
      console.log('使用模拟数据: POST /api/trades');
      return {
        code: 200,
        data: newTrade,
        message: '交易创建成功'
      };
    }
    return axios.post('/trades', data);
  },
  
  // 获取交易详情
  getTradeDetail: async (id: string | number) => {
    if (process.env.NODE_ENV === 'development') {
      await mockDelay();
      const trade = mockData.trades.find(t => t.id === Number(id));
      console.log(`使用模拟数据: /api/trades/${id}`);
      return { 
        code: trade ? 200 : 404, 
        data: trade || null, 
        message: trade ? 'success' : '交易不存在'
      };
    }
    return axios.get(`/trades/${id}`);
  },
  
  // 取消交易
  cancelTrade: async (id: string | number) => {
    if (process.env.NODE_ENV === 'development') {
      await mockDelay();
      const tradeIndex = mockData.trades.findIndex(t => t.id === Number(id));
      if (tradeIndex !== -1) {
        mockData.trades[tradeIndex].status = 'cancelled';
        console.log(`使用模拟数据: DELETE /api/trades/${id}`);
        return { code: 200, data: null, message: '交易已取消' };
      }
      return { code: 404, data: null, message: '交易不存在' };
    }
    return axios.delete(`/trades/${id}`);
  },
};

// 市场相关API
export const marketApi = {
  // 获取市场列表
  getMarkets: async () => {
    if (process.env.NODE_ENV === 'development') {
      await mockDelay();
      console.log('使用模拟数据: /api/markets');
      return { code: 200, data: mockData.markets, message: 'success' };
    }
    return axios.get('/markets');
  },
  
  // 获取市场详情
  getMarketDetail: async (symbol: string) => {
    if (process.env.NODE_ENV === 'development') {
      await mockDelay();
      const market = mockData.markets.find(m => m.symbol === symbol);
      console.log(`使用模拟数据: /api/markets/${symbol}`);
      return { 
        code: market ? 200 : 404, 
        data: market || null, 
        message: market ? 'success' : '市场不存在'
      };
    }
    return axios.get(`/markets/${symbol}`);
  },
  
  // 获取K线数据
  getKline: (params: {
    symbol: string;
    interval: string;
    limit?: number;
  }) => {
    // 简单实现，实际使用中可以生成更复杂的K线数据
    if (process.env.NODE_ENV === 'development') {
      return mockDelay().then(() => {
        const limit = params.limit || 10;
        const klineData = Array.from({ length: limit }, (_, i) => {
          const basePrice = 45000 + Math.random() * 1000;
          return {
            timestamp: Date.now() - (limit - i) * 60000, // 一分钟一根K线
            open: basePrice,
            high: basePrice + Math.random() * 100,
            low: basePrice - Math.random() * 100,
            close: basePrice + (Math.random() - 0.5) * 100,
            volume: Math.random() * 100
          };
        });
        console.log(`使用模拟数据: /api/markets/kline`);
          return { code: 200, data: klineData, message: 'success' };
        });
    }
    return axios.get('/markets/kline', { params });
  },
};

// 资产相关API
export const assetApi = {
  // 获取资产列表
  getAssets: () => axios.get('/assets'),
    
    // 获取资产详情
  getAssetDetail: (currency: string) => axios.get(`/assets/${currency}`),
    
    // 提现
  withdraw: (data: {
      currency: string;
      amount: number;
      address: string;
  }) => axios.post('/assets/withdraw', data),
};

export default {
  user: userApi,
  trade: tradeApi,
  market: marketApi,
  asset: assetApi,
};